package ontology_tools;

import com.clarkparsia.pellet.sparqldl.jena.SparqlDLExecutionFactory;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.mindswap.pellet.jena.PelletReasonerFactory;

/**
 * Clase que representa un procesador de consultas SPARQL.
 *
 * @author felipe & javi
 */
public class SparqlProcessor {

    private OntModel ontology;
    private ResultSet resultSet;

    public SparqlProcessor(String pathOntology) {
        ontology = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC);
        ontology.read(pathOntology);
    }

    /**
     * Dado una query, la ejecuta y devuleve el resultado de la misma.
     *
     * @param query Consulta a ejecutar.
     * @return Resultado de la ejecución.
     */
    public String executeQuery(String query) {
        QueryExecution queryExecution = SparqlDLExecutionFactory.create(QueryFactory.create(query), ontology);
        resultSet = queryExecution.execSelect();
        queryExecution.close();
        return formatAndTrimResult();
    }

    /**
     * Formatea y recorta el resultado de la consulta para dejarla presentable
     * al usuario.
     *
     * @return La consulta formateada y recortada.
     */
    private String formatAndTrimResult() {
        String result = ResultSetFormatter.asText(resultSet);
        StringBuilder formatedResult = new StringBuilder();
        try {
            Files.deleteIfExists(new File("./resultado.txt").toPath());
            Files.write(new File("./resultado.txt").toPath(), result.getBytes(), StandardOpenOption.CREATE);
            BufferedReader bf = new BufferedReader(new FileReader(new File("./resultado.txt")));

            String line = null;
            int opcion = 1;
            for (int i = 0; i < 4; i++) {
                line = bf.readLine();
            }
            while (line != null) {
                if (!line.contains("#Nothing") && !line.contains("-----")) {
                    line = line.replaceFirst("| ", "Recomendación " + opcion + " --->");
                    opcion++;
                    line = line.replaceAll(">", "").replaceAll("<http://www.semanticweb.org/javi/ontologies/2013/2/untitled-ontology-9#", "");
                    line = line.replace("Procesador", "Procesador: ").replace("PlacaBase", "Placa Base: ").
                            replace("Memoria", "Memoria: ").replace("DiscoD", "Disco Duro: ").
                            replace("TarjetaG", "Tarjeta Gráfica: ");
                    formatedResult.append(line).append("\n\n\n");
                }
                line = bf.readLine();
            }
        } catch (IOException ex) {
            Logger.getLogger(SparqlProcessor.class.getName()).log(Level.SEVERE, null, ex);
        }
        return formatedResult.toString();
    }
}